<!--
 * @Description: 
 * @Author: wang_k
 * @Date: 2025-08-19 09:47:49
 * @LastEditTime: 2025-08-19 14:23:34
 * @FilePath: /note/src/views/Ceshi/components/newcharts.vue
-->
<!--
 * @Description: 实际施工进度
 * @Author: wang_k
 * @Date: 2025-08-18 11:33:17
 * @LastEditTime: 2025-08-19 09:36:25
 * @FilePath: /front-end/src/modules/ModelDisplay/components/ConstructionProgressChart.vue
-->
<template>
  <div class="rock_chart">
    <!-- <SecondTitle title="实际施工进度" style="margin-bottom: 10px">
			<div class="title_right_content">
				<div class="right_title_info">
					<div class="legend">
						<div
							class="legend-item"
							v-for="(item, index) in legendData"
							:key="index"
						>
							<span
								class="legend-dot"
								:style="{
									background: item.color
								}"
							></span>
							<span class="legend-text">{{ item.text }}</span>
						</div>
						施工部位：开挖支护
					</div>
				</div>
				<img src="~@/assets/img/Cbe/narrow.png" alt="" @click="zoomHandle" />
			</div>
		</SecondTitle> -->
    <div class="trend_chart_box">
      <div class="chart_box_left">
        <div
          class="panel-item"
          v-for="item in panelData"
          :key="item.label"
          :style="`background:${item.color}`"
        >
          <div>{{ item.label }}</div>
          <div>{{ item.value }}m</div>
        </div>
      </div>
      <div class="chart_box_right">
        <div class="progress-box">
          <div class="progress-content">
            <div
              class="progress-history"
              :style="{
                width: history_width + '%',
              }"
            >
              历史态势
            </div>
            <div
              class="progress-future"
              :style="{
                width: 100 - history_width + '%',
              }"
            >
              未来态势
            </div>
          </div>
          <div class="progress-scale">
            <div
              class="progress-scale-item"
              v-for="(item, index) in xData"
              :key="item.value"
              :style="{
                width: item.width + '%',
              }"
            >
              <div class="progress-scale-line" v-show="index !== 0"></div>
              <div class="progress-scale-son" v-show="index !== 0">
                {{ dayFormat(item.value) }}
              </div>
            </div>
          </div>
          <div
            class="marking-line"
            :style="{
              left: currentPosition + '%',
            }"
          >
            <span class="line-row1">{{ markingData.date }}</span>
            <span class="line-row2">{{ markingData.meter }}</span>
          </div>
        </div>
        <div class="controls">
        <button @click="togglePlay">{{ isPlaying ? '暂停' : '播放' }}</button>
        <select v-model="playbackSpeed" @change="updateSpeed">
          <option value="0.5">x0.5</option>
          <option value="1">x1.0</option>
          <option value="2">x2.0</option>
          <option value="4">x4.0</option>
        </select>
      </div>
      </div>
    </div>
  </div>
</template>

<script>
// import SecondTitle from './RightInfoContents/SecondTitle.vue'
export default {
  name: 'ConstructionProgressChart',
  components: {
    // SecondTitle
  },
  props: {},
  data() {
    return {
      legendData: [
        {
          color: '#78CD78',
          text: '已完成',
        },
        {
          color: '#BFBFBF',
          text: '未开始',
        },
      ],
      panelData: [
        {
          label: '设计长度',
          value: '1530',
          color:
            'linear-gradient(284deg,rgba(0, 107, 237, 0) 3%,rgba(0, 107, 237, 0.15) 95%)',
        },
        {
          label: '2024年实际完成',
          value: '1530',
          color:
            'linear-gradient(284deg, rgba(149, 125, 243, 0) 3%, rgba(149, 125, 243, 0.15) 95%)',
        },
        {
          label: '2025年计划完成',
          value: '1530',
          color:
            'linear-gradient(284deg, rgba(249, 175, 85, 0) 3%, rgba(249, 175, 85, 0.15) 95%)',
        },
      ],
      markingData: {
        date: '2024-07-03',
        meter: '123m',
      },
      // currentPosition: 20,
      history_width: 40,
      isPlaying: false,
      playbackSpeed: 1, // 默认1倍速
      animationTimer: null,
      currentMonthIndex: 0, // 当前播放到的月份索引
      totalMonths: 0, // 总月份数
    };
  },
  computed: {
    xData() {
      // debugger;
      let res = [];
      let dayArr = this.generateMonthlyFirstDays();
      function calculatePercentage(part, total, decimalPlaces = 2) {
        // 处理除数为0的情况
        if (total === 0) {
          return '0';
        }
        // 计算百分比并四舍五入
        const percentage = (part / total) * 100;
        const rounded = percentage.toFixed(decimalPlaces);

        // 返回带百分号的字符串
        return `${rounded}`;
      }
      const width = calculatePercentage(1, dayArr.length);
      res = dayArr.map((item) => {
        return {
          value: item,
          width: width,
        };
      });
      console.log(res, 'xData');

      return res;
    },
    // 计算当前标记线位置百分比
    currentPosition() {
      console.log('this.currentMonthIndex->',this.currentMonthIndex,'this.totalMonths->',this.totalMonths);
      
      console.log((this.currentMonthIndex / (this.totalMonths - 1)) * 100);
      
      return (this.currentMonthIndex / (this.totalMonths - 1)) * 100;
    }
  },
  watch: {},
  created() {
    this.totalMonths = this.xData.length;
  },
  mounted() {
    // window.eventHub.$on('onProgressChange', this.handlerProgressChange)
  },
  methods: {
    // handlePlay() {
    //   if (this.isPlaying) {
    //     this.stopAnimation()
    //   } else {
    //     this.startAnimation()
    //   }
    //   this.isPlaying = !this.isPlaying
    // },
    togglePlay() {
      this.isPlaying = !this.isPlaying;
      if (this.isPlaying) {
        this.startPlayback();
      } else {
        this.pausePlayback();
      }
    },
    
    startPlayback() {
      // 清除现有定时器
      if (this.animationTimer) clearInterval(this.animationTimer);
      
      // 计算每个月的时间间隔（1倍速=5秒/月）
      const interval = 5000 / this.playbackSpeed;
      
      this.animationTimer = setInterval(() => {
        // 前进到下一月
        this.currentMonthIndex++;
        
        // 更新标记线数据
        this.updateMarkingData();
        
        // 检查是否播放完成
        if (this.currentMonthIndex >= this.totalMonths - 1) {
          this.pausePlayback();
          // 重置到初始状态
          setTimeout(() => {
            this.currentMonthIndex = 0;
            this.updateMarkingData();
          }, 1000);
        }
      }, interval);
    },
    
    pausePlayback() {
      this.isPlaying = false;
      if (this.animationTimer) {
        clearInterval(this.animationTimer);
        this.animationTimer = null;
      }
    },
    
    updateSpeed() {
      // 如果正在播放中，重新启动播放以应用新速度
      if (this.isPlaying) {
        this.pausePlayback();
        this.startPlayback();
      }
    },
    
    updateMarkingData() {
      const currentDate = this.xData[this.currentMonthIndex].value;
      // 这里根据您的业务逻辑计算米数
      // 示例：假设每个月进度增加100米
      const meters = 100 * (this.currentMonthIndex + 1);
      
      // this.markingData = {
      //   date: this.$dayjs(currentDate).format('YYYY-MM-DD'),
      //   meter: `${meters}m`
      // };
    },
    dayFormat(value) {
      return this.$dayjs(value).format('MM-DD');
      // return this.$dayjs(value).format('YYYY-MM-DD')
    },
    handlerProgressChange(data) {
      debugger;
      console.log(this.generateMonthlyFirstDays());
    },
    zoomHandle() {
      // window.eventHub.$emit('onProgressChange', { isShow: false })
    },
    generateMonthlyFirstDays(inputDate = '2024-07-05') {
      // 1. 定义起始日期（2024年7月1日）和终止日期（当前月第一天）
      const start = this.$dayjs(inputDate).startOf('month'); // 起始月第一天
      const end = this.$dayjs().startOf('month'); // 当前月第一天（避免生成未来月）
      const firstDayList = [];
      let current = start; // 循环用的当前日期

      // 2. 循环：从起始月到当前月，逐个添加每月第一天
      while (current.isBefore(end) || current.isSame(end)) {
        // 格式化为 "YYYY-MM-DD" 字符串并推入数组
        firstDayList.push(current.format('YYYY-MM-DD'));
        // 月份加1，自动处理跨年（如12月+1 → 次年1月）
        current = current.add(1, 'month');
      }
      return firstDayList;
    },
  },
  beforeDestroy() {
    this.pausePlayback();
    // window.eventHub.$on('onProgressChange', this.handlerProgressChange)
  },
};
</script>

<style scoped>
/* 添加控制按钮样式 */
.controls {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.controls button {
  padding: 5px 15px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.controls select {
  padding: 5px;
  border-radius: 4px;
}
.rock_chart {
  position: absolute;
  bottom: 74px;
  left: 23%;
  width: 55%;
  height: 25%;
  /* // width: 100%;
	// height: 100%; */
  padding: 15px;
  border-width: 3px;
  border-style: solid;
  border-color: white;
  border-radius: 12px;
  background-color: #f4f7fa;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  /* // overflow-y: hidden; */
}

.title_right_content {
  display: flex;
  align-items: center;

  .right_title_info {
    margin-right: 15px;
    font-size: 12px;
    color: #666666;
  }

  img {
    width: 14px;
    height: 14px;
    cursor: pointer;
  }
}

.trend_chart_box {
  display: flex;
  /* // flex-direction: column; */
  justify-content: space-between;
  width: 100%;
  /* // height: 158px; */
  height: calc(100% - 30px);
  position: relative;
  .chart_box_left {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: 140px;
    .panel-item {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      justify-content: center;
      padding-left: 12px;
      width: 125px;
      height: 54px;
      font-size: 14px;
      border-radius: 4px;
      box-sizing: border-box;
      border: 1px solid rgba(0, 107, 237, 0.2);
    }
  }
  .chart_box_right {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: calc(100% - 165px);
    .progress-box {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 80%;
      justify-content: center;
    }
    .progress-content {
      display: flex;
      width: 100%;
      height: 20px;
      font-size: 12px;
      background: #999;
      border-radius: 20px;
      color: #fff;
      overflow: hidden;
    }
    .progress-history {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(90deg, #97df97 0%, #63cb63 100%);
    }
    .progress-future {
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(270deg, #a1a1a1 0%, #bfbfbf 100%);
    }
    .progress-scale {
      display: flex;
      width: 100%;
      .progress-scale-item {
        position: relative;
        font-size: 12px;
        .progress-scale-line {
          width: 1px;
          height: 6px;
          background-color: #999;
        }
        .progress-scale-son {
          position: absolute;
          left: -20%;
        }
      }
    }
    .marking-line {
      position: absolute;
      top: 50%;
      bottom: 0;
      width: 0;
      height: 60%;
      border-left: 0.125rem solid #1890ff;
      transition: left 0.3s;
      z-index: 2;
      transform: translateY(-50%);
      color: #1890ff;
    }
    .marking-line:after {
      content: ''; /* 伪元素必须有 content 属性 */
      position: absolute;
      top: -5px;
      right: -4px;

      /* 三角样式 */
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-top: 5px solid #1890ff; /* 上边框有颜色，形成向下三角 */
    }
    .line-row1 {
      font-size: 12px;
      width: 70px;
      display: inline-block;
      position: absolute;
      bottom: -20px;
      left: -35px;
    }
    .line-row2 {
      font-size: 12px;
      width: 70px;
      display: inline-block;
      position: absolute;
      top: -20px;
      left: -35px;
    }
  }
}

::v-deep .SecondTitle .title {
  font-weight: bold;
}

.legend {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 32px;
  gap: 16px;

  .legend-item {
    display: flex;
    align-items: center;
    gap: 4px;

    .legend-dot {
      width: 10px;
      height: 10px;
    }

    .legend-text {
      font-size: 12px;
      color: #666;
    }
  }
}
</style>
